#include "AcceptConThread.h"
#include "ServerSocket.h"
#include "MessageRecvThread.h"
#include "MessageQueue.h"
#include "GMCreatePlayer.h"
#include "GMSetVel.h"
#include "GMCreatedPlayer.h"
#include "SendGameMessage.h"
#include "GMPingConnection.h"
#include "GMSyncTimer.h"
#include "TimerMS.h"
#include "ServerManager.h"

#include <iostream>

AcceptConThread::AcceptConThread()
{

}

AcceptConThread::AcceptConThread(int port)
{
	m_port = port;
}

void AcceptConThread::SetConPort(int port)
{
	m_port = port;
}

void AcceptConThread::Work()
{
	MutexLocker ml(&m_mutex);
	//ServerSocket ss;
	int port = m_port;
	//if (!ss.Open(port))
	//{
	//	std::cout << "Failed to open port" << std::endl;
	//	return;
	//}
	if (!TheServerManager::Instance()->Open(port))
	{
		std::cout << "Failed to open port" << std::endl;
		return;
	}
	std::cout << "server open on port:" << port << std::endl;
	std::cout << "waiting for sockets";
	int id = -1;
	while (true)
	{
		//Socket* s = ss.Accept();
		Socket* s = TheServerManager::Instance()->Accept();
		if (s)
		{
			GMCreatePlayer* gm = new GMCreatePlayer(id++);
			if (gm)
			{
				TheMsgQueue::Instance()->AddMessage(gm);
				std::cout << "Created player, id: " << id << std::endl;

				GMCreatedPlayer* gm2 = new GMCreatedPlayer(id);
				if (!SendGameMessage(*gm2, s))
				{
					std::cout << "Failed to send GMCreatedPlayer" << std::endl;
				}

				//std::cout << "paused, waiting to send sync timer" << std::endl;
				//SDL_Delay(2000);
				
				GMSyncTimer* gm3 = new GMSyncTimer();
				if (!SendGameMessage(*gm3, s))
				{
					std::cout <<"Failed to send GMSyncTimer" << std::endl;
				}

				// ping the client for lag
				GMPingConnection* gm4 = new GMPingConnection();
				if (!SendGameMessage(*gm4, s))
				{
					std::cout << "Failed to send GMPingConnection" << std::endl;
				}
				
				// add this client to the server sock
				ClientSocket* cs = (reinterpret_cast<ClientSocket*>(s));
				//ss.AddClient(cs);
				cs->SetID(id);
				TheServerManager::Instance()->AddClient(cs);
				

				MessageRecvThread* mrt = new MessageRecvThread(s);
				mrt->Start();
			}
			
		}
	}
}